<template>
  <div class="main-container">
    <el-form inline class="mb10" :model="queryParams">
      <el-form-item>
        <el-button type="primary" @click="show_classification = true">物料分类管理</el-button>
        <el-button type="primary" @click="show_dialog = true">新建物料</el-button>
      </el-form-item>
      <el-form-item label="料号"> <el-input class="w150" placeholder="请输入料号"></el-input> </el-form-item>
      <el-form-item label="品名"> <el-input class="w150" placeholder="请输入品名"></el-input> </el-form-item>
      <el-form-item label="型号"> <el-input class="w150" placeholder="请输入型号"></el-input> </el-form-item>
      <el-form-item label="品牌"> <el-input class="w150" placeholder="请输入品牌"></el-input> </el-form-item>
      <el-form-item label="状态">
        <el-select placeholder="请选择">
          <el-option label="状态A" value="状态A"> </el-option>
          <el-option label="状态B" value="状态B"> </el-option>
          <el-option label="状态C" value="状态C"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="search()">查询</el-button>
        <el-button type="primary" plain @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table border :data="materialList" :height="tableHeight" default-expand-all row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="id" label="料号" align="center" min-width="100"> </el-table-column>
      <el-table-column prop="name" label="品名" align="center" min-width="100"></el-table-column>
      <el-table-column prop="model" label="型号" align="center" min-width="100"></el-table-column>
      <el-table-column prop="brand" label="品牌" align="center" min-width="100"> </el-table-column>
      <el-table-column label="单位" align="center" min-width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.countUnit + '-' + joinArray(scope.row.units) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价额" align="center" min-width="100">
        <template slot-scope="scope">
          <p v-for="(value, index) in scope.row.price" :key="index">
            {{ value.num + value.priceUnit + '/' + value.countUnit + '-' + value.remark }}
          </p>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="备注" align="center" min-width="100"></el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="100">
        <template slot-scope="scope">
          <el-button @click="show_dialog = true" type="text" size="small">修改</el-button>
          <el-button @click="removeRow(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 物料分类管理组件 -->
    <el-drawer :visible.sync="show_classification" title="物料分类管理" :size="350">
      <el-form v-if="show_input_form" :model="currentMC" label-width="75px">
        <el-form-item label="上级分类">
          <el-cascader v-model="stock.parent" :options="data" :props="{ checkStrictly: true, expandTrigger: 'hover' }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="分类名称"> <el-input v-model="currentMC.id" placeholder="请输入分类编号"></el-input> </el-form-item>
        <el-form-item label="分类编号"> <el-input v-model="currentMC.label" placeholder="请输入分类名称"></el-input> </el-form-item>
        <el-form-item label="">
          <el-button @click="save()" type="primary" size="small">保存</el-button>
          <el-button @click="show_input_form = false" size="small">取消</el-button>
        </el-form-item>
      </el-form>
      <el-button @click="show_input_form = true" type="primary" size="small" class="ml10">添加分类</el-button>
      <el-tree :data="data" node-key="id" default-expand-all :expand-on-click-node="false">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button type="text" size="mini" @click="() => append(data)"> 添加 </el-button>
            <el-button type="text" size="mini" @click="() => remove(node, data)"> 删除 </el-button>
            <el-button type="text" size="mini" @click="() => append(data)"> 修改 </el-button>
          </span>
        </span>
      </el-tree>
    </el-drawer>

    <!-- 添加/修改物料组件 -->
    <el-dialog width="800px" class="h800" :close-on-click-modal="false" :title="dialogTitle" :visible.sync="show_dialog" append-to-body>
      <el-row class="mb20 lh40">
        <el-col :span="3" :offset="2">物料分类</el-col>
        <el-col :span="19">
          <el-cascader class="w550" v-model="currentMaterial.parent" :options="data" :props="{ checkStrictly: true, expandTrigger: 'hover' }"></el-cascader>
        </el-col>
      </el-row>

      <el-row class="mb20 lh40">
        <el-col :span="3" :offset="2">物料编号</el-col>
        <el-col :span="6">
          <el-input placeholder="请输入料号" v-model="currentMaterial.id" />
        </el-col>
        <el-col :span="3" :offset="2">物料名称</el-col>
        <el-col :span="6">
          <el-input placeholder="请输入品名" v-model="currentMaterial.name" />
        </el-col>
      </el-row>

      <el-row class="mb20 lh40">
        <el-col :span="3" :offset="2">物料品牌</el-col>
        <el-col :span="6">
          <el-autocomplete v-model="currentMaterial.brand" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect"></el-autocomplete>
        </el-col>
        <el-col :span="3" :offset="2">物料单位</el-col>
        <el-col :span="6">
          <el-select v-model="currentMaterial.countUnit" clearable placeholder="计件单位">
            <el-option v-for="item in countUnitArray" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
          <el-select v-model="currentMaterial.unit" multiple placeholder="计量单位">
            <el-option v-for="item in unitArray" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
        </el-col>
      </el-row>

      <el-row class="mb20 lh40">
        <el-col :span="3" :offset="2">物料价格</el-col>
        <el-col :span="19">
          <div v-for="(price, index) in currentMaterial.price" :key="index">
            <el-input class="w100" v-model="price.num" label="价格" />
            <el-select class="w75" v-model="price.priceUnit" placeholder="请选择">
              <el-option v-for="item in priceUnitArray" :key="item" :label="item" :value="item"> </el-option>
            </el-select>
            <el-button type="info" plain>每</el-button>
            <el-select class="w100" v-model="price.countUnit" placeholder="请选择">
              <el-option v-for="item in unitArray" :key="item" :label="item" :value="item"> </el-option>
            </el-select>
            <el-input class="w200" placeholder="备注" v-model="price.remark" />
            <el-button type="text" small @click="removePrice(index)">删除</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row class="mb20 lh40">
        <el-col :span="3" :offset="2">
          <el-button type="text" @click="addPrice()">添加价格</el-button>
        </el-col>
      </el-row>

      <el-row class="mb20 lh40">
        <el-col :span="3" :offset="2">
          <el-button type="primary" @click="save">保存</el-button>
        </el-col>
        <el-col :span="3">
          <el-button @click="show_dialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import _ from 'lodash'
@Component({
  components: {}
})
export default class SalaryDetail extends Vue {
  tableHeight: any = '800px'
  queryParams: any = {}

  /********************
   * 添加/修改物料弹框
   ********************/
  countUnitArray: any = ['根', '个', '件']
  unitArray: any = ['米', '公斤', '平方米']
  priceUnitArray: any = ['元', '日元', '美元']
  dialogTitle: string = ''
  show_dialog: boolean = false
  currentMaterial: any = {
    id: '01',
    name: '品名A',
    model: '型号',
    brand: '品牌A',
    countUnit: '根',
    units: ['米'],
    price: [{ num: 5, priceUnit: '元', countUnit: '米', remark: '采购' }]
  }
  brands: any = ['品牌A', '品牌B', '品牌C', '品牌D']
  addPrice() {
    let price = {
      num: 5,
      priceUnit: '元',
      countUnit: '米',
      remark: '采购'
    }
    this.currentMaterial.price.push(price)
  }
  removePrice(index) {
    confirm('确认删除该价格')
    this.currentMaterial.price.splice(index)
  }
  querySearch(queryString, cb) {
    let tempObjArray: any = []
    for (const iterator of this.brands) {
      let tempObj = {
        value: iterator
      }
      tempObjArray.push(tempObj)
    }
    var brands = tempObjArray
    var results = queryString ? brands.filter(this.createFilter(queryString)) : brands
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  createFilter(queryString) {
    return brands => {
      return brands.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    }
  }
  handleSelect(item) {
    console.log(item)
  }
  /****************************************
   * 物料管理组件模拟数据和代码 - BEGIN
   ****************************************/
  show_classification: boolean = false
  show_input_form: boolean = false
  currentMC = {
    id: '',
    label: '',
    parent: ''
  }
  data = [
    {
      id: 1,
      label: '1001 生产类',
      children: [
        {
          id: 4,
          label: '100101 原材料',
          children: [
            {
              id: 9,
              label: '100102 毛坯'
            },
            {
              id: 10,
              label: '100103 成品'
            }
          ]
        }
      ]
    },
    {
      id: 2,
      label: '1002 辅料',
      children: [
        {
          id: 5,
          label: '100201'
        },
        {
          id: 6,
          label: '100202'
        }
      ]
    },
    {
      id: 3,
      label: '1003',
      children: [
        {
          id: 7,
          label: '100301'
        },
        {
          id: 8,
          label: '100302'
        }
      ]
    }
  ]
  id = 20
  append(data) {
    const newChild = { id: this.id++, label: '测试分类100x', children: [] }
    if (!data.children) {
      this.$set(data, 'children', [])
    }
    data.children.push(newChild)
  }
  remove(node, data) {
    alert('如果该分类或其子分类下存在物料，不能删除')
    const parent = node.parent
    const children = parent.data.children || parent.data
    const index = children.findIndex(d => d.id === data.id)
    children.splice(index, 1)
  }
  /****************************************
   * 物料管理组件模拟数据和代码 - END
   ****************************************/

  /****************************************
   * 物料表格数据 - BEGIN
   ****************************************/
  materialList: any = [
    { id: '01', name: '品名A', model: '型号', brand: '品牌A', countUnit: '根', units: ['米'], price: [{ num: 5, priceUnit: '元', countUnit: '米', remark: '采购' }] },
    {
      id: '02',
      name: '品名B',
      model: '型号',
      brand: '品牌B',
      countUnit: '件',
      units: ['米', '公斤'],
      price: [
        { num: 5, priceUnit: '元', countUnit: '米', remark: '采购' },
        { num: 10, priceUnit: '元', countUnit: '公斤', remark: '采购' }
      ]
    },
    { id: '03', name: '品名C', model: '型号', brand: '品牌C', countUnit: '个', units: ['米'], price: [{ num: 5, priceUnit: '元', countUnit: '米', remark: '采购' }] }
  ]
  joinArray(array) {
    let result = ''
    if (Array.isArray(array) && array.length > 0) {
      result += array[0]
      for (let i = 1; i < array.length; i++) {
        result += '-' + array[i]
      }
    }
    return result
  }
  removeRow(row) {
    confirm('确认删除物料：' + row.name + '?')
  }
  /****************************************
   * 物料表格数据 - END
   ****************************************/

  drawerTitle: any = ''

  stockList: any = []

  stockOptions: any = [
    { value: '01', label: '原材料库' },
    { value: '02', label: '毛坯库' },
    { value: '03', label: '成品库' },
    {
      value: '04',
      label: '供方库',
      children: [
        { value: '0401', label: '供方甲库位' },
        { value: '0402', label: '供方已库位' }
      ]
    }
  ]
  stock: any = {
    id: '',
    name: '',
    level: 1,
    content: '',
    remark: ''
  }
  created() {
    // 获取屏幕高度 设置表格高度
    let screenHeight = document.documentElement.clientHeight
    console.log('获取到的屏幕高度：' + screenHeight)
    this.tableHeight = screenHeight - 230 + 'px'
  }
  createMaterial() {
    this.drawerTitle = '新建仓库'
    this.show_classification = true
    this.stock = {
      id: '',
      name: '',
      level: 1,
      content: '',
      remark: '',
      parent: ''
    }
  }
  reset() {
    alert('刷新页面')
  }
  modify(row) {
    this.drawerTitle = '修改仓库'
    this.show_classification = true
    this.stock = _.cloneDeep(row)
  }

  save() {
    alert('提交保存')
  }
  parentStockChange(parent) {
    console.log('parent')
    console.log(parent)
    console.log('this.stock')
    console.log(this.stock)

    if (parent.length == 0) {
      // 如果清空，则是1级仓库
      this.stock.level = 1
      this.stock.id = ''
    } else {
      // 如果选择，则为上层仓库的下一级，且编号随上层仓库
      let choosedParentId = parent.pop()
      console.log('choosedParentId')
      console.log(choosedParentId)

      let parentStock
      let findOne = this.stockList.some(function findParent(item) {
        console.log('some find ing')
        console.log(item)

        if (item.id == choosedParentId) {
          parentStock = item
          return true
        }
        return Array.isArray(item.children) && item.children.some(findParent)
      })
      console.log('findOne')
      console.log(findOne)

      // let parentStock = this.stockList.filter(item => item.id == parent[0])[0]
      console.log('parentStock')
      console.log(parentStock)

      this.stock.level = parentStock.level + 1
      this.stock.parent = parentStock.id
      this.stock.id = parentStock.id

      console.log('this.stock')
      console.log(this.stock)
    }
  }
}
</script>

<style >
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>